package com.axend.aerosense.common.connect;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager.NetworkCallback;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.PatternMatcher;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.axend.aerosense.base.app.BaseApplication;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.utils.BleUtils;
import com.axend.aerosense.base.utils.ToastUtils;
import com.axend.aerosense.base.utils.WifiUtils;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.connect.bean.BleScanResultBean;
import com.axend.aerosense.common.connect.bean.DeviceConnectType;
import com.axend.aerosense.common.connect.bean.WifiScanResultBean;
import com.axend.aerosense.common.connect.impl.IBleConnect;
import com.axend.aerosense.common.connect.impl.IConnectCallback;
import com.axend.aerosense.common.connect.impl.IDeviceConnect;
import com.axend.aerosense.common.connect.impl.IScanCallback;
import com.axend.aerosense.common.connect.impl.IScanResult;
import com.axend.aerosense.common.connect.impl.IScanStateCallback;
import com.axend.aerosense.common.connect.tcp.IDeviceConnectCallback;
import com.axend.aerosense.common.connect.tcp.NettyClient;
import com.blankj.utilcode.util.LogUtils;

import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 连接设备
 * 不可使用单例模式
 */
@SuppressLint("MissingPermission")
public class DeviceConnectManager {

    /**
     * 单位：毫秒
     * wifi扫描超时、wifi连接超时、蓝牙扫描最大时长
     */
    private static final int TIME_OUT = 12 * 1000;

    private static final long BLE_SCAN_INTERVAL = 5000L;

    private ConnectivityManager connectivityManager;
    private NetworkSpecifier specifier;
    private NetworkRequest request;
    private NetworkCallback networkCallback;
    private Activity context;
    private IDeviceConnect deviceConnect;

    private WifiUtils wifiUtils;
    private BroadcastReceiver broadcastReceiver;
    private Map<String, IScanResult> wifiScanResultMap;
    private IScanCallback scanCallback;
    private IntentFilter wifiConnectFilter;
    private IntentFilter scanResultFilter;
    private Handler delayedTaskHandler;
    private Runnable delayedTaskRunnable;
    private String wifiSsid;
    private IDeviceConnectCallback iDeviceConnectCallback;
    private DeviceConnectType connectType;
    private Network networkSocket;
    private boolean isRegister = false;
    private BluetoothAdapter.LeScanCallback leScanCallback;
    private ScanSettings bleScanSettings;
    private ScanCallback bleScanCallback;
    private List<ScanFilter> scanFilters;
    private long lastTime;
    private int bleScanCount = 0;

    public DeviceConnectManager(Activity context){
        if (null == context) {
            LogUtils.w("Context 或者 IDeviceConnect不能为空");
            return;
        }
        this.context = context;
        this.wifiUtils = WifiUtils.getInstance();
        init();
    }

    public void setDeviceConnect(IDeviceConnect deviceConnect) {
        this.deviceConnect = deviceConnect;
        this.connectType = getConnectType();
        this.deviceConnect.setCallback(new IConnectCallback() {
            @Override
            public void state(int state) {
                boolean result = state == IConnectCallback.STATE_SUCCESS;
                if (isWifiConnectType() && isAndroid10() && result) {
                    //P2P连接（仅安卓10及以上支持）
                    bindSocket();
                    return;
                }
                callbackDevConnectStatus(result);
            }

            @Override
            public void readData(Object message) {
                callbackDeviceData(message);
            }
        });
    }

    private void init(){
        if (isEmpty(wifiConnectFilter)){
            wifiConnectFilter = new IntentFilter();
            //接收wifi的连接状态
            wifiConnectFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
            wifiConnectFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            wifiConnectFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        }

        if (isEmpty(scanResultFilter)) {
            scanResultFilter = new IntentFilter();
            scanResultFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);  //扫描完成结果
        }

        wifiScanResultMap = new HashMap<>();
    }

    //注册广播
    private void register(IntentFilter intentFilter){
        //如果广播为空，则注册广播，避免重复注册
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)){
                    //扫描完成，通知拿wifi扫描结果
                    handlerWifiScanResult();
                } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
                    //wifi连接成功回调
                    handlerWifiConnect(intent);
                }
            }
        };
        //注册
//        if(Build.VERSION.SDK_INT == 33) {
//            context.registerReceiver(broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
//        }else {
//            context.registerReceiver(broadcastReceiver, intentFilter);
//        }
        context.registerReceiver(broadcastReceiver, intentFilter);

        isRegister = true;
    }

    /**
     * 注销广播
     * 使用完成一个，注销一个，避免重复回调
     */
    private void unregister(){
        if (broadcastReceiver != null && isRegister){
            context.unregisterReceiver(broadcastReceiver);
            isRegister = false;
        }
    }

    /** wifi连接结果处理 */
    private void handlerWifiConnect(Intent intent) {
        NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (info.getState().equals(NetworkInfo.State.CONNECTED)){
            // 延时建立socket连接，防止wifi没有连接好建立连接
            new Handler().postDelayed(()->{
                //如果连接的wifi名字一样，则连接设备wifi成功
                if (isWifiConnected(wifiSsid)){
                    LogUtils.d("WIFI连接成功，开始创建TCP连接");
                    //建立tcp连接
                    deviceConnect.connect();
                    removeDelayedTask();
                }else {
                    //否则回调连接设备失败
                    handlerConnectBroken();
                }
            }, 4000);
            unregister();
        }
    }

    /** 处理Wifi的扫描结果并回调 */
    private void handlerWifiScanResult() {
        LogUtils.d("WIFI扫描成功，回调！");
        List<ScanResult> results = wifiUtils.getScanResults();
        for (ScanResult result : results){
            String ssid = result.SSID;
            int frequency = result.frequency;
            //过滤隐藏Wifi和5G频段wifi
            if (!"".equals(ssid) && !wifiUtils.is5GHz(frequency)){
                wifiScanResultMap.put(
                        ssid,
                        new WifiScanResultBean(
                                ssid,
                                WifiManager.calculateSignalLevel(result.level, 101)
                        )
                );
            }
        }

        //扫描完成回调
        callbackScanResult(new ArrayList<>(wifiScanResultMap.values()));
        removeDelayedTask();
        unregister();
    }



    /**
     * 处理Wifi连接中断情况
     */
    private void handlerConnectBroken() {
        LiveDatabus.getInstance()
                .with(Gobal.EVENT_KEY.CONNECT_BROKEN, Boolean.class)
                .postValue(true);
        callbackDevConnectStatus(false);
    }

    /** 手机扫描wifi延时任务 */
    private void wifiScanDelayTask(){
        createDelayedTask(()->{
            callbackScanResult(new ArrayList<>(wifiScanResultMap.values()));
            unregister();
        }, TIME_OUT);
    }

    /** 手机连接设备wifi延时任务 */
    private void wifiConnectDelayTask(){
        createDelayedTask(()-> {
            callbackDevConnectStatus(false);
            unregister();
        }, TIME_OUT);
    }

    /**
     * 创建延时任务
     * @param runnable 任务
     * @param delayed  延时（毫秒）
     */
    private void createDelayedTask(Runnable runnable, int delayed){
        this.delayedTaskRunnable = runnable;

        if (null == delayedTaskHandler) {
            delayedTaskHandler = new Handler(Looper.getMainLooper());
        }
        delayedTaskHandler.postDelayed(delayedTaskRunnable, delayed);
    }

    /** 移除延时任务 */
    private void removeDelayedTask(){
        if (null == delayedTaskHandler || null == delayedTaskRunnable){
            return;
        }

        delayedTaskHandler.removeCallbacks(delayedTaskRunnable);
        this.delayedTaskHandler = null;
    }



    /**
     * 适用于Android 10及以上的版本连接wifi。
     * 在连接wifi时，同时创建Tcp连接，并绑定Socket到当前网络（P2P）
     * @param wifiName
     */
    private void connectDevWifiByApi30(String wifiName){
        //Android 版本10及以上版本，使用此方式连接设备WiFi
        if (isAndroid10()){
            specifier = new WifiNetworkSpecifier.Builder()
                    .setSsidPattern(new PatternMatcher(wifiName, PatternMatcher.PATTERN_PREFIX))
                    //.setWpa2Passphrase("tvt-2018")
                    .build();

            request = new NetworkRequest.Builder()
                    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                    .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
                    .setNetworkSpecifier(specifier)
                    .build();

            connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (networkCallback == null) {
                networkCallback = new NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
                        LogUtils.d("onAvailable");
                        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
                        boolean isCapWifi = capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
                        //此网络是否使用wifi传输
                        if (isCapWifi) {
                            if (isAndroid10()) {
                                //将网络绑定到当前进程
                                connectivityManager.bindProcessToNetwork(network);
                            } else {
                                ConnectivityManager.setProcessDefaultNetwork(network);
                            }

                            DeviceConnectManager.this.networkSocket = network;
                            deviceConnect.connect();
                            //下面将network绑定到Socket，在连接成功后的回调进行绑定
                        }else {
                            handlerConnectBroken();
                        }
                    }

                    @Override
                    public void onUnavailable() {
                        super.onUnavailable();
                        LogUtils.d("onUnavailable");
                        callbackDevConnectStatus(false);
                    }
                };
            }
            connectivityManager.requestNetwork(request, networkCallback);
            //connectivityManager.registerNetworkCallback();
        }
    }

    private void bindSocket(){
        if (null == networkSocket) {
            LogUtils.w("networkSocket为空！");
            callbackDevConnectStatus(false);
            return;
        }
        try {
            //将Socket对象绑定到当前wifi网络
            Socket socket = ((NettyClient) deviceConnect).getSocket();
            networkSocket.bindSocket(socket);
            callbackDevConnectStatus(true);
        } catch (Exception e) {
            e.printStackTrace();
            //连接成功的情况下会抛出此异常
            callbackDevConnectStatus(e.getMessage().equals("Socket is connected"));
        }
    }

    private void unbindSocket(){
        if (isWifiConnectType()){
            if (isAndroid10()){
                //需要注销wifi连接监听
                if (null != networkCallback && null != connectivityManager){
                    //解除与当前进程的绑定，否则会出现App无法联网的情况
                    try{
                        connectivityManager.bindProcessToNetwork(null);
                        connectivityManager.unregisterNetworkCallback(networkCallback);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    /** 回调设备连接状态 */
    private void callbackDevConnectStatus(boolean b){
        if (null != iDeviceConnectCallback){
            try{
                iDeviceConnectCallback.isConnectSuccess(b);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    /** 回调设备数据 */
    private void callbackDeviceData(Object message){
        if (null != iDeviceConnectCallback){
            try{
                iDeviceConnectCallback.deviceData(message);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    /** 返回扫描结果 */
    private void callbackScanResult(List<IScanResult> list){
        if (null != scanCallback) {
            try{
                scanCallback.scanResult(list);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    private void callbackScanState(int state){
        if (null != scanCallback && scanCallback instanceof IScanStateCallback) {
            try{
                ((IScanStateCallback) scanCallback).scanState(state);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    /** 判断对象是否为空 */
    private boolean isEmpty(Object obj){
        return null == obj;
    }

    /** 当前是否已连接指定wifi */
    private boolean isWifiConnected(String wifiName){
        String wifiSSID = wifiUtils.getWifiSSID();
        if (!TextUtils.isEmpty(wifiSSID) && !TextUtils.isEmpty(wifiName)){
            return wifiName.equals(wifiSSID);
        }else {
            return false;
        }
    }

    /** 是否为wifi连接类型 */
    private boolean isWifiConnectType(){
        return this.connectType == DeviceConnectType.TYPE_WIFI;
    }

    /** 蓝牙扫描配置 */
    private ScanSettings getBleScanSettings(){
        if (null == bleScanSettings){
            bleScanSettings = new ScanSettings.Builder()
                    //连续不断的扫描， 建议应用在前台时使用。但会消耗比较多的电量。 扫描结果也会比较快一些。
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    //只有搜索到第一个与筛选设备匹配时回调， 随后扫描到其他设备不进行回调。
                    .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES )
                    //需要收到设备比较强大的信号才能搜索到
                    .setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
                    //控制需要匹配多少设备
                    //.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
                    //你可以设置扫描结果回调的延时，如果延时时间大于0，Android将会收集搜索结果，并在延迟时间到达后通知。
                    // 这种情况会回调onBatchScanResults方法， 而不是onScanResult 方法。
//                    .setReportDelay(BLE_SCAN_INTERVAL)
                    .build();
        }
        return bleScanSettings;
    }

    private ArrayList<android.bluetooth.le.ScanResult> bleScanResults = new ArrayList<>();

    /**
     * 蓝牙扫描回调
     * @return
     */
    private ScanCallback getBleScanCallback(){
        if (null == bleScanCallback){
            bleScanCallback = new ScanCallback(){
                @Override
                public void onScanResult(int callbackType, android.bluetooth.le.ScanResult result) {
                    super.onScanResult(callbackType, result);
                    LogUtils.d("onScanResult", result);
                    long currentTime = System.currentTimeMillis();
                    boolean find = false;
                    for (android.bluetooth.le.ScanResult item:bleScanResults) {
                        if(item.getDevice().equals(result.getDevice())) {
                            find = true;
                            break;
                        }
                    }
                    if(!find && currentTime - lastTime <= BLE_SCAN_INTERVAL * 2){
                        bleScanResults.add(result);
                    }

                    if((currentTime - lastTime > BLE_SCAN_INTERVAL * 2)){
                        lastTime = System.currentTimeMillis();
                        List<IScanResult> list = getRadarList(bleScanResults);
                        bleScanResults.clear();
                        stopBleScan();
                        removeBleScanDelayedTask();
                        callbackScanResult(list);
                        callbackScanState(IScanStateCallback.SCAN_COMPLETE);
                    }
                }

                @Override
                public void onBatchScanResults(List<android.bluetooth.le.ScanResult> results) {
                    super.onBatchScanResults(results);
                    //此处同一时间会回调两次，防抖处理
//                    long currentTime = System.currentTimeMillis();
//                    if (currentTime - lastTime > 500) {
//                        LogUtils.d("onBatchScanResults", results.size());
//                        handlerBleScanResult(results);
//                    }
//                    lastTime = currentTime;
                }

                @Override
                public void onScanFailed(int errorCode) {
                    super.onScanFailed(errorCode);
                    LogUtils.w("onScanFailed", errorCode);
                    String[] permissions = new String[]{
                            Manifest.permission.BLUETOOTH,
                            Manifest.permission.BLUETOOTH_CONNECT,
                            Manifest.permission.BLUETOOTH_SCAN,
                            Manifest.permission.BLUETOOTH_ADVERTISE,
                            "android.permission.NEARBY_WIFI_DEVICES"
                    };
                    boolean p = false;
                    for (String permission : permissions) {
                        int per = ContextCompat.checkSelfPermission(context, permission);
                        if (PackageManager.PERMISSION_GRANTED != per) {
                            p = true;
                            LogUtils.w("required permission not granted . permission = " + permission);
                        }
                    }
                    callbackScanState(IScanStateCallback.SCAN_FAILED);
                }
            };
        }
        return bleScanCallback;
    }

    private List<IScanResult> getRadarList(List<android.bluetooth.le.ScanResult> results){
        List<IScanResult> list = new ArrayList<>();
        if (null == results || results.isEmpty()) { return list; }
        for (android.bluetooth.le.ScanResult result : results) {
            String name = result.getDevice().getName();
            if (TextUtils.isEmpty(name) || name.length() < 6) { continue; }
            LogUtils.d("wifi name:" + name);
            RadarType type = RadarType.getType(name);
            if (null != type) {
                list.add(new BleScanResultBean(name, type, result.getDevice()));
            }
        }
        return list;
    }

    /** 处理蓝牙扫描的结果 */
    private void handlerBleScanResult(List<android.bluetooth.le.ScanResult> results){
        if (null == results || results.isEmpty()) { return; }

        List<IScanResult> list = new ArrayList<>();
        for (android.bluetooth.le.ScanResult result : results) {
            String name = result.getDevice().getName();
            if (TextUtils.isEmpty(name) || name.length() < 6) { continue; }
            LogUtils.d("wifi name:" + name);
            RadarType type = RadarType.getType(name);
            if (null != type) {
                list.add(new BleScanResultBean(name, type, result.getDevice()));
            }
        }

        if (list.isEmpty()) {
            return;
        }

        //扫描到设备，停止扫描、移除延时任务、回调扫描结果、回调扫描完成
        stopBleScan();
        removeBleScanDelayedTask();
        callbackScanResult(list);
        callbackScanState(IScanStateCallback.SCAN_COMPLETE);

        //如果蓝牙扫描的总时间超过10秒，则停止扫描，下面通过扫描间隔时间计算扫描的次数
//        int temp = (int) (((10L * 1000) / BLE_SCAN_INTERVAL) + 0.5);
//        bleScanCount++;
//        if (bleScanCount >= temp) {
//            stopBleScan();
//            //回调扫描完成
//            callbackScanState(IScanStateCallback.SCAN_COMPLETE);
//            bleScanCount = 0;
//        }
    }

    /** 创建蓝牙扫描延时任务 */
    private void startBleScanDelayedTask(){
        createDelayedTask(()-> {
            stopBleScan();
            callbackScanState(IScanStateCallback.SCAN_COMPLETE);
        }, TIME_OUT);
    }

    /** 移除蓝牙扫描延时任务 */
    private void removeBleScanDelayedTask(){
        removeDelayedTask();
    }

    /*=============================================================================================*/

    /** 获取当前连接实例 */
    public IDeviceConnect getTcpClient() {
        return deviceConnect;
    }

    /** 使用完成，必须释放资源 */
    public void close(){
        unbindSocket();
        if (null != deviceConnect){
            deviceConnect.close();
        }
    }

    public void clear(){
        networkCallback = null;
        connectivityManager = null;
        iDeviceConnectCallback = null;
        deviceConnect = null;
        wifiUtils = null;
        scanCallback = null;
        context = null;
    }

    public DeviceConnectType getConnectType(){
        if (null == deviceConnect) {
            LogUtils.w("deviceConnect为空");
            return null;
        }
        return deviceConnect.getConnectType();
    }

    /**
     * 连接wifi，并检查wifi的连接状态
     * 如果设备已连接，并创建TCP连接，则回调成功
     * 如果设备是安卓10以下版本，如果连接了wifi，则直接创建Tcp连接
     * @param wifiName
     */
    public void connectWifi(String wifiName){
        this.wifiSsid = wifiName;
        //如果Tcp已建立连接，则回调成功
        if (isDevConnected()){
            callbackDevConnectStatus(true);
            return;
        }

        if (isWifiConnected(wifiName)) {
            if (isAndroid10()) {
                //使用点对点连接WIFI，再创建Tcp连接
                connectDevWifiByApi30(wifiName);
                return;
            }
            //wifi已连接，创建TCP连接
            deviceConnect.connect();
        } else {
            if (isAndroid10()) {
                //使用点对点连接WIFI，再创建Tcp连接
                connectDevWifiByApi30(wifiName);
                return;
            }

            //安卓10以下的机型，使用API方式连接WIFI，再创建TCP连接
            register(wifiConnectFilter);
            wifiUtils.connectWifi(wifiName, "", "");
            wifiConnectDelayTask();
        }
    }

    /**
     * 连接设备蓝牙
     */
    public void connectBluetooth(RadarType radarType){
        if (!isWifiConnectType()){
            if (deviceConnect instanceof IBleConnect) {
                ((IBleConnect) deviceConnect).setDeviceName(radarType.getNameByString());
            }
            deviceConnect.connect();
        }
    }

    public void sendMessage(Object entity){
        if (!isDevConnected()) return;

        deviceConnect.sendMsg(entity);
    }

    /** 扫描wifi */
    public void scanWifi(){
        if (wifiScanResultMap.size() > 0){
            callbackScanResult(new ArrayList<>(wifiScanResultMap.values()));
        }else {
            register(scanResultFilter);
            wifiUtils.startScan();  //开始扫描
            wifiScanDelayTask();
        }
    }

    /** 重新扫描wifi */
    public void reScanWifi(){
        if (null != wifiScanResultMap) {
            wifiScanResultMap.clear();
        }
        register(scanResultFilter);
        wifiUtils.startScan();  //开始扫描
        wifiScanDelayTask();
    }

    /** 设备是否连接成功 */
    public boolean isDevConnected(){
        if (null != deviceConnect){
            return deviceConnect.isConnect();
        }else {
            return false;
        }
    }

    /** 开始扫描蓝牙 */
    public void startBleScan(){
//        if (null == leScanCallback) {
//            leScanCallback = (device, rssi, scanRecord) -> {
//                //扫描结果是一个个回调的，使用map集合存储
//                String name = device.getName();
//                if (TextUtils.isEmpty(name)) {
//                    return;
//                }
//
//                String address = device.getAddress();
//                bleScanResultMap.put(
//                        address,
//                        new BleScanResultBean(name, device)
//                );
//            };
//        }

//        if (null == scanFilters || scanFilters.isEmpty()){
//            scanFilters = new ArrayList<>();
//            RadarType[] types = RadarType.values();
//            //只通过名字扫描
//            for (RadarType type : types) {
//                if (RadarType.ASSURE.getNameByString().equals(type.getNameByString())) {
//                    // ASSURE雷达不参与蓝牙搜索
//                    continue;
//                }
//                ScanFilter filter = new ScanFilter.Builder()
//                        .setDeviceName(type.getNameByString())
//                        .build();
//                scanFilters.add(filter);
//            }
//        }

//        BleUtils.getInstance()
//                .getBluetoothAdapter()
//                .startLeScan(leScanCallback);

        String[] permissions = new String[]{
                Manifest.permission.BLUETOOTH,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION ,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_ADVERTISE,
                "android.permission.NEARBY_WIFI_DEVICES"
        };
        boolean p = false;
        for (String permission : permissions) {
            int per = ContextCompat.checkSelfPermission(context, permission);
            if (PackageManager.PERMISSION_GRANTED != per) {
                p = true;
                LogUtils.w("required permission not granted . permission = " + permission);
            }
        }
        LogUtils.d("开始扫描蓝牙");
        ScanFilter filter = new ScanFilter.Builder().build();
        ArrayList<ScanFilter> fl = new ArrayList<ScanFilter>();
//        fl.add(filter);
        requestPermission();
        BleUtils.getInstance()
                .getLeScanner()
                .startScan(fl, getBleScanSettings(), getBleScanCallback());
        lastTime = System.currentTimeMillis();
//        startBleScanDelayedTask();
    }

    private void requestPermission() {
        //动态申请是否有必要看sdk版本哈
        if (Build.VERSION.SDK_INT < 23 || null == context || Build.VERSION.SDK_INT > 32 ){return;}
        //判断是否有权限
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }

    /** 停止扫描蓝牙 */
    public void stopBleScan(){
        if (null == bleScanCallback) { return; }
//        BleUtils.getInstance()
//                .getBluetoothAdapter()
//                .stopLeScan(leScanCallback);

        LogUtils.d("停止扫描蓝牙");
        BleUtils.getInstance()
                .getLeScanner()
                .stopScan(getBleScanCallback());

    }

    /** 获取扫描结果 */
//    public List<IScanResult> getScanResult(){
//        List<IScanResult> results;
//        switch (deviceConnect.getConnectType()) {
//            case TYPE_WIFI:
//                results = new ArrayList<>(wifiScanResultMap.values());
//                break;
//            case TYPE_BLE:
//                results = new ArrayList<>(bleScanResultMap.values());
//                if (bleScanResultMap.size() > 0) {
//                    //拿到结果，清除缓存,清除之前的缓存
//                    bleScanResultMap.clear();
//                }
//                break;
//            default:
//                return null;
//        }
//        return results;
//    }

    /**
     * 检查设备连接状态
     * 如果设备未连接则回调连接失败
     */
    public void checkDeviceConnect(){
        callbackDevConnectStatus(null != deviceConnect && deviceConnect.isConnect());
    }

    /** 是否是安卓10及以上的版本 */
    public boolean isAndroid10(){
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
    }

    /** 设置扫描结果回调 */
    public void setScanCallback(@NonNull IScanCallback scanCallback) {
        this.scanCallback = scanCallback;
    }

    /** 设置设备连接回调 */
    public void setDeviceConnectCallback(IDeviceConnectCallback iDeviceConnectCallback) {
        this.iDeviceConnectCallback = iDeviceConnectCallback;
    }
}
